package cc.booku.owlbox.BottomFragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.RequiresApi;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.CollectionStation_norm.CS_FileScannerActivity;
import cc.booku.owlbox.FileName_A;
import cc.booku.owlbox.FileName_C;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.FileOperations.ShareUtils;
import cc.booku.owlbox.HomeDirectory.HomeDirectoryActivity;
import cc.booku.owlbox.OnlineDatabase.OnlineDatabaseActivity;
import cc.booku.owlbox.R;
import cc.booku.owlbox.UserSettingsPage.loadSearchActivity;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link fragment_notice.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link fragment_notice#newInstance} factory method to
 * create an instance of this fragment.
 */
public class fragment_notice extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private Toolbar Toolbar;

    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator;
    private List<FileName_C> fileName_cList = new ArrayList<FileName_C>();
    private static final int WHAT_LOADING = 0;
    private TDialog tDialog;
    private ListView list_filename;
    private LinearLayout ll_nofile;
    private TextView tv_qq, fromfileurl, Tv_sizedata;

    public fragment_notice() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment fragment_notice.
     */
    // TODO: Rename and change types and number of parameters
    public static fragment_notice newInstance(String param1, String param2) {
        fragment_notice fragment = new fragment_notice();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_notice, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        //ll_nofile = (LinearLayout) getActivity().findViewById(R.id.ll_nofile);
        LoadToolbar();
        LoadControl();
        Shuaxin();
        try {
            //申请SD卡读写的权限
            FileoOperations.verifyStoragePermissions(getActivity());
            //创建文件夹
            FileoOperations.makeRootDirectory(filePath);
            ReadDisplayDir(filePath);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "读取文件目录失败" + "\n" + "如果您拒绝了存储权限请卸载重新安装", Toast.LENGTH_SHORT).show();
//异常处理
        }
        fromfileurl = (TextView) getActivity().findViewById(R.id.fromfileurl);
        fromfileurl.setText(filePath);

        super.onActivityCreated(savedInstanceState);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    private void LoadControl() {
        ll_nofile = (LinearLayout) getActivity().findViewById(R.id.ll_nofile);
        list_filename = (ListView) getActivity().findViewById(R.id.list_filename);
        tv_qq = (TextView) getActivity().findViewById(R.id.tv_qq);
        Tv_sizedata = (TextView) getActivity().findViewById(R.id.sizedata);
        tv_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    SystemUtil.joinQQGroup(getActivity(), "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                } catch (Exception e) {
                    //异常处理
                    tv_qq.setText("打开失败！点击重试~");
                }
            }
        });


    }

    private void LoadToolbar() {
        Toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                Intent intent = new Intent(getActivity(), HomeDirectoryActivity.class);
                startActivity(intent);
            }
        });
        Toolbar.inflateMenu(R.menu.menu_fragment_folder);
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_folder:
                        Intent intent = new Intent(getContext(), HomeDirectoryActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.action_offline:
                        Intent intent_offline = new Intent(getContext(), loadSearchActivity.class);
                        startActivity(intent_offline);
                        break;
                }
                return true;
            }
        });

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_fragment_folder, menu);
    }

    private void Shuaxin() {

//            WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//            DisplayMetrics dm = new DisplayMetrics();
//            wm.getDefaultDisplay().getMetrics(dm);
//            int width = dm.widthPixels;         // 屏幕宽度（像素）
//            int height = dm.heightPixels;       // 屏幕高度（像素）
//            float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//            int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//            // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
//            int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
//            int screenHeight = (int) (height / density);// 屏幕高度(dp)

        Tv_sizedata.setText("[刷新页面]");
        Tv_sizedata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {


                    try {

                        //刷新

                        fileName_cList.clear();
                        ReadDisplayDir(filePath);

                        if (list_filename.getCount() == 0) {
                            ll_nofile.setVisibility(View.VISIBLE);
                            //Toast.makeText(MainoldActivity.this, "list_filename", Toast.LENGTH_SHORT).show();
                        } else if (list_filename.getCount() >= 1) {
                            list_filename.setVisibility(View.VISIBLE);

                        }

                        Tv_sizedata.setText("刷新成功");

                    } catch (Exception e) {

                        Tv_sizedata.setText("刷新失败");
//异常处理
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Tv_sizedata.setText("Ends justify the means");
                        }
                    }, 2000);
                } catch (Exception e) {
                    //异常处理
                    Tv_sizedata.setText("刷新失败");
                }

            }
        });


    }

    public FileName_A fileName_a;
    public FileName_C fileName_c;

    private void ReadDisplayDir(String DirPath) {

        fileName_cList.clear();

        Log.e("111", "path" + DirPath);
        ArrayList<String> ss = FileoOperations.getFileName(DirPath, ".txt");
        for (String s : ss) {
            Log.e("111", "result:" + getCount(s, "_"));
            fileName_c = new FileName_C();
//            //String str = "大地云视频_erotic_情色_20200516.txt";
            String[] str1 = s.split("\\.");

            if (3 == getCount(str1[0], "_")) {
                String[] strs = str1[0].split("_");

                String owlTitle = strs[0];//文件标题
                String owlNorm = strs[1];//解析规范
                String owlType = strs[2];//文件类型
                String owlTime = strs[3];//更新时间


                Log.e("111", "owlTitle:" + owlTitle + "-----owlNorm:" + owlNorm + "-----owlType:" + owlType + "----owlTime:" + owlTime);

                fileName_c.setOwlTitle(owlTitle);//发送到实体类
                fileName_c.setOwlNorm(owlNorm);
                fileName_c.setOwlType(owlType);
                fileName_c.setOwlTime(owlTime);//添加到对象集合中
                fileName_cList.add(fileName_c);
            } else continue;

        }
        Message msg = new Message();
        msg.what = 9;
        handler.sendMessage(msg);//用activity中的handler发送消息

    }

    public int getCount(String str, String key) {
        if (str == null || key == null || "".equals(str.trim()) || "".equals(key.trim())) {
            return 0;
        }
        int count = 0;
        int index = 0;
        while ((index = str.indexOf(key, index)) != -1) {
            index = index + key.length();
            count++;
        }
        return count;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 9:
                    ClickFileName((ArrayList<FileName_C>) fileName_cList);

                    Refresh();
                    break;

                case WHAT_LOADING:
                    if (tDialog != null) {
                        tDialog.dismiss();
                    }
                    return;
            }
        }
    };


    private void Refresh() {
        try {
            if (list_filename.getCount() == 0) {
                ll_nofile.setVisibility(View.VISIBLE);
                //Toast.makeText(MainoldActivity.this, "list_filename", Toast.LENGTH_SHORT).show();
            } else if (list_filename.getCount() >= 1) {
                list_filename.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            Log.e("--Method--", "refresh失败");
//异常处理
        }
    }

    public void ClickFileName(ArrayList<FileName_C> fileName_cList) {


        fileName_a = new FileName_A(R.layout.filename_item, getActivity(), fileName_cList);


        list_filename.setAdapter(fileName_a);
        //点按操作

        list_filename.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                // owlTitle,owlNorm,owlType,owlTime;
                final TextView owlTitle = (TextView) view.findViewById(R.id.owlTitle);
                final TextView owlNorm = (TextView) view.findViewById(R.id.owlNorm);

                final TextView owlType = (TextView) view.findViewById(R.id.owlType);
                final TextView owlTime = (TextView) view.findViewById(R.id.owlTime);


                String OwlTitle = owlTitle.getText().toString();
                String OwlNorm = owlNorm.getText().toString();
                String OwlType = owlType.getText().toString();
                String OwlTime = owlTime.getText().toString();

                //指定文件链接
                String specifiedFile = filePath + OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt";

                /*
                 *
                 * 普通视频：OrdinaryVideo_C
                 * 普通书籍:OrdinaryBooks
                 *
                 * */


                if ("CollectionStation".equals(OwlNorm)) {

                    //跳转到FileScannerActivity打开指定文件
                    Intent intent = new Intent(getContext(), CS_FileScannerActivity.class);

                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为specifiedFile
                    bundle.putString("SpecifiedFile", specifiedFile);
                    intent.putExtras(bundle);

                    startActivity(intent);

                } else if ("OnlineDatabase".equals(OwlNorm)) {
                    //跳转到FileScannerActivity打开指定文件
                    Intent intent = new Intent(getContext(), OnlineDatabaseActivity.class);
                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为specifiedFile
                    bundle.putString("OwlTitle", OwlTitle);
                    bundle.putString("SpecifiedFile", specifiedFile);
                    intent.putExtras(bundle);
                    startActivity(intent);

                } else {

                    Toast.makeText(getContext(), "请修改数据规范", Toast.LENGTH_SHORT).show();
                }


            }
        });

        //长按操作
        list_filename.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, final View view,
                                           final int i, long l) {


                final TextView owlTitle = (TextView) view.findViewById(R.id.owlTitle);
                final TextView owlNorm = (TextView) view.findViewById(R.id.owlNorm);

                final TextView owlType = (TextView) view.findViewById(R.id.owlType);
                final TextView owlTime = (TextView) view.findViewById(R.id.owlTime);


                String OwlTitle = owlTitle.getText().toString();
                String OwlNorm = owlNorm.getText().toString();
                String OwlType = owlType.getText().toString();
                String OwlTime = owlTime.getText().toString();

                //指定文件链接
                String FileUrl = filePath + OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt";
                DialogFilechanges(FileUrl, OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt");

                return true;     // 这里一定要改为true，代表长按自己消费掉了，若为false，触发长按事件的同时，还会触发点击事件</span></strong>
            }
        });


    }


    private void DialogFilechanges(final String FileUrl, String Filename) {

        new TDialog.Builder(getFragmentManager())
                .setLayoutRes(R.layout.tdialog_longduration)
                .setScreenWidthAspect(getActivity(), 1.0f)
                .setGravity(Gravity.CENTER)
                .addOnClickListener(R.id.tv_blank, R.id.tv_delete, R.id.tv_rename, R.id.tv_share, R.id.tv_share_qq)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        switch (view.getId()) {
                            case R.id.tv_share_qq:
                                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                                        PackageManager.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        makeAnExtraRequest();
                                    }
                                } else {
                                    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename);
                                    ShareUtils.shareQQFriend(getContext(), f, Filename);
                                }

                                break;

                            case R.id.tv_share:

                                // 将上面获取到的imageUri再一次进行转化， 把他变成系统可以识别的Uri
                                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                                        PackageManager.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        makeAnExtraRequest();
                                    }
                                } else {
                                    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename);
                                    ShareUtils.shareWechatFriend(getActivity(), f, Filename);
                                }

                                tDialog.dismiss();
                                break;
                            case R.id.tv_blank:
                                //对文件重命名，添加“不显示_”
                                //修改1路径就可以
                                String blankurl = FileUrl.replace("OwlDatabase/", "OwlDatabase/不显示_");
                                FileoOperations.renameFile(FileUrl, blankurl);
                                tDialog.dismiss();
                                break;
                            case R.id.tv_delete:
                                FileoOperations.deleteFile(getActivity(), FileUrl);

                                tDialog.dismiss();
                                break;
                            case R.id.tv_rename:

                                String Str[] = FileUrl.split("OwlDatabase/");
                                DialogRename(Str[1]);
                                tDialog.dismiss();
                                break;

                        }
                        //更新listview
                        fileName_cList.clear();
                        ReadDisplayDir(filePath);

                    }
                })

                .create()
                .show();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void makeAnExtraRequest() {
        int code = 100;
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        for (String string : permissions) {
            if (getActivity().checkSelfPermission(string) != PackageManager.PERMISSION_GRANTED) {
                getActivity().requestPermissions(permissions, code);
                code++;
                return;
            }
        }
    }

    private void DialogRename(final String Filename) {


        new TDialog.Builder(getFragmentManager())
                .setLayoutRes(R.layout.tdialog_rename)
                .setScreenWidthAspect(getActivity(), 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.editText, Filename);
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {


                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:
                                //String blankurl = content.replace("OwlDatabase/不显示_","OwlDatabase/");
                                FileoOperations.renameFile(filePath + Filename, filePath + content);
                                tDialog.dismiss();
                                break;

                        }


                    }
                })

                .create()
                .show();
    }

}
